﻿using CommonUtility;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;

namespace WPay.Infrastructure.Unity
{
    public class CSVFileHelper
    {
        /// <summary>
        /// 将DataTable中数据写入到CSV文件中
        /// </summary>
        /// <param name="dt">提供保存数据的DataTable</param>
        /// <param name="fileName">CSV的文件路径</param>
        public static void SaveCSV(DataTable dt, string fullPath)
        {
            FileInfo fi = new FileInfo(fullPath);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }
            FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
            string data = "";
            //写出各行数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                data = "";
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string str = dt.Rows[i][j].ToString();
                    str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
                    if (str.Contains(',') || str.Contains('"')
                        || str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
                    {
                        str = string.Format("\"{0}\"", str);
                    }
                    data += str;
                    if (j < dt.Columns.Count - 1)
                    {
                        data += ",";
                    }
                }
                sw.WriteLine(data);
            }
            sw.Close();
            fs.Close();
        }


        /// <summary>
        /// 将DataTable中数据写入到CSV文件中(包含表头)
        /// </summary>
        /// <param name="dt">提供保存数据的DataTable</param>
        /// <param name="fileName">CSV的文件路径</param>
        public static void SaveCSVAndHeader(DataTable dt, string fullPath)
        {
            FileInfo fi = new FileInfo(fullPath);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }
            FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
            string data = "";



            if (dt != null && dt.Columns.Count > 0 && dt.Rows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (i > 0)
                    {
                        sb.Append(",");
                    }
                    sb.Append("\"").Append(dt.Columns[i].ColumnName.ToString().Replace("\"", "")).Append("\"");
                }
                sw.WriteLine(sb.ToString());
            }
            //写出各行数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                data = "";
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string str = dt.Rows[i][j].ToString();
                    str = str.Replace("\"", "");//替换英文冒号 英文冒号需要换成两个冒号
                    if (str.Contains(',') || str.Contains('"')
                        || str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
                    {
                        str = string.Format("\"{0}\"", str);
                    }
                    data += str;
                    if (j < dt.Columns.Count - 1)
                    {
                        data += ",";
                    }
                }
                sw.WriteLine(data);
            }
            sw.Close();
            fs.Close();
        }

        /// <summary>
        /// 将CSV文件的数据读取到DataTable中
        /// </summary>
        /// <param name="fileName">CSV文件路径</param>
        /// <returns>返回读取了CSV数据的DataTable</returns>
        public static DataTable OpenCSV(string filePath, int n, Stream fs = null)
        {
            System.Data.DataTable dt = new System.Data.DataTable();

            try
            {

                using (
                   var filestream = fs != null ? fs : (new System.IO.FileStream(filePath, System.IO.FileMode.Open,
                       System.IO.FileAccess.Read, FileShare.Read)))
                {
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    var clums = 0;
                    using (var reader = new StreamReader(filestream, Encoding.GetEncoding("gb2312"), false))
                    {
                        int m = 0;
                        while (!reader.EndOfStream)
                        {
                            m = m + 1;
                            string str = reader.ReadLine();
                            string[] split = str.Split(',');

                            if (m == n)
                            {
                                clums = split.Length;
                                System.Data.DataColumn column; //列名  
                                for (int c = 0; c < split.Length; c++)
                                {
                                    column = new System.Data.DataColumn();
                                    column.DataType = System.Type.GetType("System.String");
                                    column.ColumnName = split[c];
                                    if (dt.Columns.Contains(split[c]))                 //重复列名处理  
                                        column.ColumnName = split[c] + c;
                                    dt.Columns.Add(column);
                                }
                            }
                            if (m >= n + 1)
                            {
                                try
                                {
                                    System.Data.DataRow dr = dt.NewRow();
                                    for (int i = 0; i < split.Length; i++)
                                    {
                                        if (i > clums - 1)
                                        {
                                            dr[clums - 1] += split[i];
                                        }
                                        else
                                        {
                                            dr[i] = split[i];
                                        }

                                    }
                                    dt.Rows.Add(dr);
                                }
                                catch (Exception e)
                                {
                                    LoggerHelper.Log("" + e.Message + e.InnerException?.Message);

                                }
                            }

                        }
                    }
                }
                GC.Collect();
                GC.Collect(1);

            }
            catch (Exception e)
            {
                LoggerHelper.Log("" + e.Message + e.InnerException?.Message);

            }
            return dt;
        }
        public static DataTable OpenCSV2(string filePath, int n, bool isheader = true, Stream fs = null)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            try
            {

                using (
                   var filestream = fs != null ? fs : (new System.IO.FileStream(filePath, System.IO.FileMode.Open,
                       System.IO.FileAccess.Read, FileShare.Read)))
                {
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    var clums = 0;
                    using (var reader = new StreamReader(filestream, Encoding.GetEncoding("gb2312"), false))
                    {
                        int m = 0;
                        while (!reader.EndOfStream)
                        {
                            m = m + 1;
                            string str = reader.ReadLine();
                            string[] split = str.Split(',');

                            if (m == n)
                            {
                                clums = split.Length;
                                System.Data.DataColumn column; //列名  
                                for (int c = 0; c < split.Length; c++)
                                {
                                    if (!isheader)
                                    {
                                        dt.Columns.Add("column" + c);
                                    }
                                    else
                                    {
                                        column = new System.Data.DataColumn();
                                        column.DataType = System.Type.GetType("System.String");
                                        column.ColumnName = split[c];
                                        if (dt.Columns.Contains(split[c]))                 //重复列名处理  
                                            column.ColumnName = split[c] + c;
                                        dt.Columns.Add(column);
                                    }

                                }
                            }
                            if (m >= n)
                            {
                                try
                                {
                                    System.Data.DataRow dr = dt.NewRow();
                                    for (int i = 0; i < split.Length; i++)
                                    {
                                        if (i > clums - 1)
                                        {
                                            dr[clums - 1] += split[i];
                                        }
                                        else
                                        {
                                            dr[i] = split[i];
                                        }

                                    }
                                    dt.Rows.Add(dr);
                                }
                                catch (Exception e)
                                {
                                    LoggerHelper.Log("" + e.Message + e.InnerException?.Message);

                                }
                            }

                        }
                    }
                }
                GC.Collect();
                GC.Collect(1);

            }
            catch (Exception e)
            {
                LoggerHelper.Log("" + e.Message + e.InnerException?.Message);

            }
            return dt;
        }
        public static DataTable OpenCSVutf(string filePath, int n, Stream fs = null)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            try
            {

                using (
                   var filestream = fs != null ? fs : (new System.IO.FileStream(filePath, System.IO.FileMode.Open,
                       System.IO.FileAccess.Read, FileShare.Read)))
                {
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    var clums = 0;
                    using (var reader = new StreamReader(filestream, Encoding.GetEncoding("utf-8"), false))
                    {
                        int m = 0;
                        while (!reader.EndOfStream)
                        {
                            m = m + 1;
                            string str = reader.ReadLine().Replace("\"", "");
                            string[] split = str.Split(',');

                            if (m == n)
                            {
                                clums = split.Length;
                                System.Data.DataColumn column; //列名  
                                for (int c = 0; c < split.Length; c++)
                                {
                                    column = new System.Data.DataColumn();
                                    column.DataType = System.Type.GetType("System.String");
                                    column.ColumnName = split[c];
                                    if (dt.Columns.Contains(split[c]))                 //重复列名处理  
                                        column.ColumnName = split[c] + c;
                                    dt.Columns.Add(column);
                                }
                            }
                            if (m >= n + 1)
                            {
                                try
                                {
                                    System.Data.DataRow dr = dt.NewRow();
                                    for (int i = 0; i < split.Length; i++)
                                    {
                                        if (i > clums - 1)
                                        {
                                            dr[clums - 1] += split[i];
                                        }
                                        else
                                        {
                                            dr[i] = split[i];
                                        }

                                    }
                                    dt.Rows.Add(dr);
                                }
                                catch (Exception e)
                                {
                                    LoggerHelper.Log("" + e.Message + e.InnerException?.Message);

                                }
                            }

                        }
                    }
                }
                GC.Collect();
                GC.Collect(1);

            }
            catch (Exception e)
            {
                LoggerHelper.Log("" + e.Message + e.InnerException?.Message);

            }
            return dt;
        }
    }
}
